package com.example.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.entity.StudentBean;
import com.example.demo.entity.TeacherBean;

import java.util.Calendar;

/**
 * 教育系统JWT工具类，用于处理学生和讲师的token
 */
public class EduJwtUtil {
    // 加密secret
    private static final String SECRET = "EDU-ONLINE-SYSTEM";
    // 过期时间
    private static final Integer TIME_OUT_DAY = 30;
    // 需要重新生成的天数 如果token的时间超过这个 则重新生成token
    private static final Integer NEED_CREATE_DAY = 7;
    
    /**
     * 生成学生token
     * @param student 学生信息
     * @return token字符串
     */
    public static String createStudentToken(StudentBean student) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, TIME_OUT_DAY);
        String token = JWT.create()
                .withClaim("userId", student.getId())
                .withClaim("userType", "student")
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }
    
    /**
     * 生成讲师token
     * @param teacher 讲师信息
     * @return token字符串
     */
    public static String createTeacherToken(TeacherBean teacher) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, TIME_OUT_DAY);
        String token = JWT.create()
                .withClaim("userId", teacher.getId())
                .withClaim("userType", "teacher")
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }
    
    /**
     * 获取token信息 如果token有误则返回null
     * @param token JWT token
     * @return 解码后的JWT
     */
    public static DecodedJWT getTokenInfo(String token) {
        try {
            return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 获取用户ID
     * @param decodedJWT 解码后的JWT
     * @return 用户ID
     */
    public static Integer getUserId(DecodedJWT decodedJWT) {
        return decodedJWT.getClaim("userId").asInt();
    }
    
    /**
     * 获取用户类型
     * @param decodedJWT 解码后的JWT
     * @return 用户类型（student/teacher）
     */
    public static String getUserType(DecodedJWT decodedJWT) {
        return decodedJWT.getClaim("userType").asString();
    }
}
